package cn.web.demo.controller;

import cn.web.demo.model.*;
import cn.web.demo.service.IUserService;
import cn.web.demo.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService iUserService;

    @Autowired
    RoleService roleService;

    @RequestMapping("/list")
    public String list(){
        return "/user/list";
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public PageResult<User> orderjson(User courseOrder, int page, int limit){
        PageResult<User> pageResult=iUserService.findPageResult(courseOrder, page, limit);
        return pageResult;
    }

    @RequestMapping("/add")
    public String add(Model model){
      List<Role> list= roleService.findAllRoles();
      model.addAttribute("list",list);
        return "/user/add";
    }

    @RequestMapping("/edit")
    public String edit(Model model,Integer id){
        List<Role> list= roleService.findAllRoles();
        model.addAttribute("user",iUserService.findUserAndRolesByUserId(id));
        model.addAttribute("list",list);
        model.addAttribute("roles",iUserService.findUserAndRolesByUserId(id).getRoles());
        return "/user/edit";
    }

    @RequestMapping("save")
    @ResponseBody
    public CouresResult save(User user,Integer [] RoleId){
        CouresResult couresResult=new CouresResult();
        iUserService.save(user, RoleId);
        return couresResult;
    }
}
